package com.lap.gateway.service;

import com.lap.gateway.entity.acl.Api;
import com.lap.gateway.tools.Constant;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class PermissionMatcher {
  public static final Pattern PATTERN = Pattern.compile(Constant.REGEX);

  public Optional<Api> match(List<Api> apis, String uri, String method) {
    if (apis == null || apis.isEmpty()) return Optional.empty();

    return apis.stream()
        .filter(
            api -> {
              String patternUri = resolvePattern(api);
              return Pattern.matches(patternUri, uri) && method.equalsIgnoreCase(api.getMethod());
            })
        .findFirst();
  }

  private String resolvePattern(Api api) {
    StringBuilder result = new StringBuilder();
    if (StringUtils.isNotBlank(api.getModule())) {
      result
          .append(api.getModule().startsWith(Constant.SLASH) ? Constant.BLANK : Constant.SLASH)
          .append(api.getModule());
    }
    if (StringUtils.isNotBlank(api.getUri())) {
      result
          .append(api.getUri().startsWith(Constant.SLASH) ? Constant.BLANK : Constant.SLASH)
          .append(api.getUri());
    }
    return PATTERN.matcher(result.toString()).replaceAll(Constant.REPLACE_PATTERN);
  }
}
